import os, platform
from django.views.generic import View
from django.http import JsonResponse, Http404
from django.shortcuts import render
from index.views import ResultMixin
import json
import time
import shutil
import zipfile, rarfile, tarfile


class GetPathFielsView(ResultMixin, View):
    def post(self, request, **kwargs):
        data = []
        path = request.POST.get("path")
        path = json.loads(path)  # 解码

        # 如果是windows系统就得转换一下
        if path == "/" and platform.system() == "Windows":
            path = "c:/"

        try:
            dirs = os.listdir(path)
        except OSError as e:
            print(e)
            return JsonResponse(self.make_result(code=400, error=str(e)))

        # 遍历此路径
        for file in dirs:
            f_dict = {}
            # 绝对路径
            file_dir = os.path.join(path, file).replace("\\", "/")
            if os.path.isdir(file_dir):
                # 是目录
                f_dict["is_folder"] = True
                f_dict["path"] = file_dir
                f_dict["name"] = file
                ctime = time.localtime(os.path.getctime(file_dir))
                f_dict["ctime"] = time.strftime("%Y-%m-%d %H:%M", ctime)
                f_dict["size"] = None
                f_dict["chmod"] = oct(os.stat(file_dir).st_mode)[-3:]
            else:
                # 是文件
                f_dict["is_folder"] = False
                f_dict["path"] = file_dir
                f_dict["name"] = file
                ctime = time.localtime(os.path.getctime(file_dir))
                f_dict["ctime"] = time.strftime("%Y-%m-%d %H:%M", ctime)
                f_dict["size"] = os.path.getsize(file_dir)
                f_dict["chmod"] = oct(os.stat(file_dir).st_mode)[-3:]
            data.append(f_dict)
            data = sorted(data, key=lambda d: d["is_folder"], reverse=True)

        return JsonResponse(self.make_result(data=data))


class GetPathSizeView(ResultMixin, View):
    def post(self, request, **kwargs):
        path = request.POST.get("path", None)
        if not path:
            raise Http404
        size = 0
        for root, dirs, files in os.walk(path):
            size += sum([os.path.getsize(os.path.join(root, name).replace("\\", "/")) for name in files])
        return JsonResponse(self.make_result(data=size))


class MoveFileView(ResultMixin, View):
    def post(self, request, **kwargs):
        old_path = request.POST.get("old_path", None)
        new_path = request.POST.get("new_path", None)
        if not old_path or not new_path:
            raise Http404

        if not os.path.exists(old_path):
            return JsonResponse(self.make_result(code=400, error="没有这个文件或目录,请刷新"))
        try:
            shutil.move(old_path, new_path)
        except OSError as e:
            return JsonResponse(self.make_result(code=400, error="剪切失败: " + str(e)))

        return JsonResponse(self.make_result())


class CopyFileView(ResultMixin, View):
    def post(self, request, **kwargs):
        old_path = request.POST.get("old_path", None)
        new_path = request.POST.get("new_path", None)
        if not old_path or not new_path:
            raise Http404

        if not os.path.exists(old_path):
            return JsonResponse(self.make_result(code=400, error="没有这个文件或目录,请刷新"))
        if os.path.isdir(old_path):
            # 文件夹
            try:
                shutil.copytree(old_path, new_path)
            except OSError as e:
                return JsonResponse(self.make_result(code=400, error="复制目录失败: " + str(e)))

            return JsonResponse(self.make_result())
        else:
            # 文件
            try:
                shutil.copy(old_path, new_path)
            except OSError as e:
                return JsonResponse(self.make_result(code=400, error="复制文件失败: " + str(e)))

            return JsonResponse(self.make_result())


class UnZipView(ResultMixin, View):
    def post(self, request, **kwargs):
        file_path = request.POST.get("file_path", None)
        jy_path = request.POST.get("jy_path", None)
        file_pwd = request.POST.get("file_pwd", None)
        if not file_path or not jy_path:
            raise Http404
        print(file_path, '###', jy_path)
        if not os.path.exists(file_path):
            return JsonResponse(self.make_result(code=400, error="没有这个文件或目录,请刷新"))

        # 文件
        name, hz = os.path.splitext(file_path)
        if hz == ".zip":
            # 解压zip
            with zipfile.ZipFile(file_path.replace("\\", "/"), "r") as zf:
                zf.extractall(path=jy_path, pwd=file_pwd)
            return JsonResponse(self.make_result())
        elif hz == ".rar":
            with rarfile.RarFile(file_path.replace("\\", "/"), "r") as rf:  # 待解压文件
                rf.extractall(jy_path, pwd=file_pwd)
            return JsonResponse(self.make_result())
        elif hz == ".tar":
            # tar
            with tarfile.TarFile(file_path.replace("\\", "/"), "r") as tf:  # 待解压文件
                tf.extractall(path=jy_path)
            return JsonResponse(self.make_result())
        elif hz == ".gz":
            # gz
            with tarfile.TarFile(file_path.replace("\\", "/"), "r:gz") as tf:  # 待解压文件
                tf.extractall(path=jy_path)
            return JsonResponse(self.make_result())

        return JsonResponse(self.make_result())


class ZipView(ResultMixin, View):
    def post(self, request, **kwargs):
        file_path = request.POST.get("file_path", None)
        ys_path = request.POST.get("ys_path", None)
        ys_type = request.POST.get("type", "tar")
        if not file_path or not ys_path:
            raise Http404
        print(file_path, '###', ys_path, "###", ys_type)
        if not os.path.exists(file_path):
            return JsonResponse(self.make_result(code=400, error="没有这个文件或目录,请刷新"))

        # 得到文件名
        file_name = file_path.split("/")[-1]
        # 去掉后缀
        name, hz = os.path.splitext(file_name)
        if ys_type == "tar":
            t = tarfile.open(ys_path + "/" + name + ".tar", "w")
            for root, dir, files in os.walk(file_path):
                for file in files:
                    fullpath = os.path.join(root, file)
                    t.add(fullpath)
            t.close()
        elif ys_type == "zip":
            with zipfile.ZipFile(ys_path + "/" + name + ".tar", "w") as t:
                for root, dir, files in os.walk(file_path):
                    for file in files:
                        fullpath = os.path.join(root, file)
                        t.write(fullpath)
                t.close()
        elif ys_type == "gz":
            t = tarfile.open(ys_path + "/" + name + ".tar.gz", "w:gz")
            for root, dir, files in os.walk(file_path):
                for file in files:
                    fullpath = os.path.join(root, file)
                    t.add(fullpath)
            t.close()
        else:
            return JsonResponse(self.make_result(code=400, data="不支持的压缩格式"))

        # 文件
        return JsonResponse(self.make_result())


class NewFileView(ResultMixin, View):
    def post(self, request, **kwargs):
        root_path = request.POST.get('path', None)
        file_name = request.POST.get("file_name", None)
        if not file_name and not root_path:
            raise Http404

        # 创建文件
        path = os.path.join(root_path, file_name).replace("\\", "/")
        if platform.system() == "Windows":
            with open(path, "wb") as t:
                t.close()
        else:
            os.mknod(path)
        return JsonResponse(self.make_result())


class NewFolderView(ResultMixin, View):
    def post(self, request, **kwargs):
        root_path = request.POST.get('path', None)
        folder_name = request.POST.get("folder_name", None)
        if not folder_name and not root_path:
            raise Http404

        # 创建文件夹
        path = os.path.join(root_path, folder_name).replace("\\", "/")
        os.mkdir(path)
        return JsonResponse(self.make_result())


class SetChmodView(ResultMixin, View):
    def post(self, request, **kwargs):
        name_path = request.POST.get('path_name', None)
        chmod = request.POST.get("chmod", None)
        if not name_path and not chmod:
            raise Http404

        # 判断系统类型
        if platform.system() == "Windows":
            return JsonResponse(self.make_result(code=400, error="对不起,该系统类型暂不支持"))
        else:
            os.system("chmod -R " + chmod + " " + name_path)
        return JsonResponse(self.make_result())


class DelFolderView(ResultMixin, View):
    def post(self, request, **kwargs):
        name_path = request.POST.get('path_name', None)
        if not name_path:
            raise Http404
        # 判断系统类型
        try:
            if platform.system() == "Windows":
                # 剪切到回收站
                shutil.move(name_path, "e:/RecycleBin/")
            else:
                shutil.move(name_path, "/home/RecycleBin/")
        except shutil.Error as e:
            return JsonResponse(self.make_result(code=400, error=str(e)))
        return JsonResponse(self.make_result())


class ImgShowView(ResultMixin, View):
    def post(self, request, **kwargs):
        name_path = request.POST.get('path_name', None)
        if not name_path and os.path.exists(name_path):
            raise Http404
        # 吧这个文件拷贝到静态目录
        pwd = os.getcwd()
        path = os.path.join(pwd, "static", "temporary").replace("\\", "/")

        shutil.copy(name_path, path)
        name, hz = os.path.splitext(name_path)
        img_path = os.path.join("temporary", name.split("/")[-1] + hz).replace("\\", "/")
        return JsonResponse(self.make_result(data=img_path))
